package vn.vfriends.games.jpa.controller;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceUnit;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import vn.vfriends.games.jpa.entity.Page;
import vn.vfriends.games.jpa.entity.Role;
import vn.vfriends.games.jpa.controller.exceptions.NonexistentEntityException;
import vn.vfriends.games.jpa.controller.exceptions.RollbackFailureException;

/**
 *
 * @author tuan@vfriends.vn
 */
public class PageJpaController implements Serializable {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "vfGamesPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Page page) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Role role = page.getRole();
            if (role != null) {
                role = em.getReference(role.getClass(), role.getId());
                page.setRole(role);
            }
            em.persist(page);
            if (role != null) {
                role.getPages().add(page);
                role = em.merge(role);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Page page) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Page persistentPage = em.find(Page.class, page.getId());
            Role oldRole = persistentPage.getRole();
            Role newRole = page.getRole();
            if (newRole != null) {
                newRole = em.getReference(newRole.getClass(), newRole.getId());
                page.setRole(newRole);
            }
            page = em.merge(page);
            if (oldRole != null && !oldRole.equals(newRole)) {
                oldRole.getPages().remove(page);
                oldRole = em.merge(oldRole);
            }
            if (newRole != null && !newRole.equals(oldRole)) {
                newRole.getPages().add(page);
                newRole = em.merge(newRole);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = page.getId();
                if (findPage(id) == null) {
                    throw new NonexistentEntityException("The page with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Page page;
            try {
                page = em.getReference(Page.class, id);
                page.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The page with id " + id + " no longer exists.", enfe);
            }
            Role role = page.getRole();
            if (role != null) {
                role.getPages().remove(page);
                role = em.merge(role);
            }
            em.remove(page);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Page> findPages() {
        return findPages(true, -1, -1);
    }

    public List<Page> findPages(int maxResults, int firstResult) {
        return findPages(false, maxResults, firstResult);
    }

    private List<Page> findPages(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Page.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Page findPage(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Page.class, id);
        } finally {
            em.close();
        }
    }

    public Page findPageByName(String name){
        EntityManager em = getEntityManager();
        try{
        Query query = em.createNamedQuery("Page.findByName", Page.class);
        query.setParameter("name", name);
        List<Page> pageList = query.getResultList();
        if(pageList != null && !pageList.isEmpty())
            return pageList.get(0);
        else
            return null;
        } finally {
            em.close();
        }
    }
    
    public Page findPageByLink(String link){
        EntityManager em = getEntityManager();
        try{
        Query query = em.createNamedQuery("Page.findByLink", Page.class);
        query.setParameter("link", link);
        List<Page> pageList = query.getResultList();
        if(pageList != null && !pageList.isEmpty())
            return pageList.get(0);
        else
            return null;
        } finally {
            em.close();
        }
    }
    
    public int getPageCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Page> rt = cq.from(Page.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
